<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition End User License Agreement
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magento.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    Mage
 * @package     Mage_Adminhtml
 * @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
 * @license http://www.magento.com/license/enterprise-edition
 */

/**
 * Adminhtml customer grid block
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Silk_Qslb_Block_Adminhtml_Catalog_Product_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

    public function __construct()
    {
        parent::__construct();
        $this->setId('productGrid');
        $this->setDefaultSort('entity_id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
        $this->setVarNameFilter('product_filter');

    }

    protected function _getStore()
    {
        $websiteId = Mage::helper("qslb")->_getwebsiteId();
        return Mage::getModel('core/website')->load($websiteId)->getDefaultStore();
        //$storeId = (int) $this->getRequest()->getParam('store', 0);
        //return Mage::app()->getStore($storeId);
    }

    /****************************Aitoc_Aitquantitymanager_Block_Rewrite_AdminCatalogProductGrid*****************************/
    protected function _prepareCollection()
    {
        $store = $this->_getStore();
        if($store){
            $websiteId = $store->getWebsiteId();
        }else{
            echo "你是超级管理员请到商品库管理商品！";
            return false;
        }
       

        $collection = Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToSelect('sku')
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('barcode')
            ->addAttributeToSelect('item_no')
            ->addAttributeToSelect('price')
            ->addAttributeToSelect('attribute_set_id')
            ->addAttributeToSelect('type_id')
            ->addAttributeToSelect('manufacturer_id')
            ->addAttributeToSelect('thumbnail')
            ->addAttributeToSelect('status')
            ->addAttributeToSelect('tag')
            ->addWebsiteFilter($websiteId);
        if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
            $collection->joinField('qty',
                'cataloginventory/stock_item',
                'qty',
                'product_id=entity_id',
                '{{table}}.stock_id=1 AND {{table}}.website_id = ' . $websiteId,
                'left');
        }
       if ($store->getId()) {
            //$collection->setStoreId($store->getId());
            $adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
            $collection->addStoreFilter($store);
            $collection->joinAttribute(
                'name',
                'catalog_product/name',
                'entity_id',
                null,
                'inner',
                $adminStore
            );
            $collection->joinAttribute(
                'custom_name',
                'catalog_product/name',
                'entity_id',
                null,
                'inner',
                $store->getId()
            );
            $collection->joinAttribute('store_title', 'catalog_product/title', 'entity_id', null, 'left', $store->getId());
            $collection->joinAttribute('store_location', 'catalog_product/location', 'entity_id', null, 'left', $store->getId());
            $collection->joinAttribute('special_price', 'catalog_product/special_price', 'entity_id', null, 'left', $store->getId());
            $collection->joinAttribute(
                'status',
                'catalog_product/status',
                'entity_id',
                null,
                'inner',
                $store->getId()
            );
            $collection->joinAttribute(
                'visibility',
                'catalog_product/visibility',
                'entity_id',
                null,
                'inner',
                $store->getId()
            );
           // $collection->joinAttribute(
           //     'dealer_id',
           //     'catalog_product/dealer_id',
           //     'entity_id',
           //     null,
           //     'inner',
           //     $store->getId()
           // );
            $collection->joinAttribute(
                'price',
                'catalog_product/price',
                'entity_id',
                null,
                'left',
                $store->getId()
            );
            $collection->joinAttribute(
                'tag',
                'catalog_product/tag',
                'entity_id',
                null,
                'left',
                $store->getId()
            );
        }
        else {
            
            $collection->addAttributeToSelect('price');
            $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
            $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');
        }
        $collection->getSelect()->group("e.entity_id");
        $this->setCollection($collection);

        parent::_prepareCollection();
        $this->getCollection()->addWebsiteNamesToResult();
        return $this;
    }

    protected function _addColumnFilterToCollection($column)
    {
        if ($this->getCollection()) {
            if ($column->getId() == 'websites') {
                $this->getCollection()->joinField('websites',
                    'catalog/product_website',
                    'website_id',
                    'product_id=entity_id',
                    null,
                    'left');
            }
        }
        return parent::_addColumnFilterToCollection($column);
    }

    protected function _prepareColumns()
    {
        $store = $this->_getStore();
        if($store){
            $websiteId = $store->getWebsiteId();
        }else{
            return false;
        }
        $zgb = Mage::helper('zgb');
        $session = Mage::getSingleton('admin/session');
        $roleId = $session->getUser()->getRoleId();

        $this->addColumn('entity_id',
            array(
                'header'=> Mage::helper('catalog')->__('ID'),
                'width' => '50px',
                'type'  => 'number',
                'index' => 'entity_id',
        ));

        $this->addColumn('img',
            array(
                'header'=> Mage::helper('catalog')->__('产品缩略图'),
                'index' => 'entity_id',
                'renderer' => 'Silk_Zgb_Block_Renderer_Thumbnail',
                'width' => '80px'

        ));

        $store = $this->_getStore();

        if ($store && $store->getId()) {
            $this->addColumn('custom_name',
                array(
                    'header'=> Mage::helper('catalog')->__('Name in %s', $store->getName()),
                    'index' => 'custom_name',
            ));
            $this->addColumn('title',
                array(
                    'header'=> Mage::helper('catalog')->__('商品副标题'),
                    'index' => 'store_title',
                    'width' =>"200px",
            ));
        }
        else
        {
            $this->addColumn('name',
                array(
                    'header'=> Mage::helper('catalog')->__('Name'),
                    'index' => 'name',
            ));
        }

        // $this->addColumn('type',
        //     array(
        //         'header'=> Mage::helper('catalog')->__('Type'),
        //         'width' => '60px',
        //         'index' => 'type_id',
        //         'type'  => 'options',
        //         'options' => Mage::getSingleton('catalog/product_type')->getOptionArray(),
        // ));

        // $sets = Mage::getResourceModel('eav/entity_attribute_set_collection')
        //     ->setEntityTypeFilter(Mage::getModel('catalog/product')->getResource()->getTypeId())
        //     ->load()
        //     ->toOptionHash();

        // $this->addColumn('set_name',
        //     array(
        //         'header'=> Mage::helper('catalog')->__('Attrib. Set Name'),
        //         'width' => '100px',
        //         'index' => 'attribute_set_id',
        //         'type'  => 'options',
        //         'options' => $sets,
        // ));


        $this->addColumn('sku',
            array(
                'header'=> Mage::helper('catalog')->__('SKU'),
                'width' => '80px',
                'index' => 'sku',
        ));
        $this->addColumn('barcode',
            array(
                'header'=> Mage::helper('catalog')->__('条形码'),
                'width' => '80px',
                'index' => 'barcode',
        ));
        $this->addColumn('store_location',
            array(
                'header'=> Mage::helper('catalog')->__('货位'),
                'width' => '80px',
                'index' => 'location',
        ));
        $categorys = $zgb->getSubCategorys();

        $this->addColumn('category',
                array(
                    'header'=> Mage::helper('catalog')->__('分类'),
                    'width' => '100px',
                    'index' => 'category_id',
                    'type'  => 'options',
                    'options' => $categorys,
                    'renderer' => 'Silk_Zgb_Block_Renderer_Category',
                    'filter_condition_callback' => array($this, 'filterCategoryCallback')
        ));

        $this->addColumn('item_no',
            array(
                'header'=> Mage::helper('catalog')->__('商品编码'),
                'width' => '80px',
                'index' => 'item_no',
        ));

        $store = $this->_getStore();
        $this->addColumn('price',
            array(
                'header'=> Mage::helper('catalog')->__('Price'),
                'type'  => 'price',
                'currency_code' => $store?$store->getBaseCurrency()->getCode():null,
                'index' => 'price',
        ));

        $this->addColumn('special_price',
                array(
                    'header'=> Mage::helper('catalog')->__('Special Price'),
                    'type'  => 'price',
                    'currency_code' => $store->getBaseCurrency()->getCode(),
                    'index' => 'special_price',
            ));

        if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
            $this->addColumn('qty',
                array(
                    'header'=> Mage::helper('catalog')->__('Qty'),
                    'width' => '100px',
                    'type'  => 'number',
                    'index' => 'qty',
            ));
        }

        // $this->addColumn('visibility',
        //     array(
        //         'header'=> Mage::helper('catalog')->__('Visibility'),
        //         'width' => '70px',
        //         'index' => 'visibility',
        //         'type'  => 'options',
        //         'options' => Mage::getModel('catalog/product_visibility')->getOptionArray(),
        // ));

      /*  if($store && $store->getId())
        {

            $this->addColumn('status_at', array(
                'header' => Mage::helper('sales')->__('启用/禁用时间'),
                'index' => 'status_at',
                'filter_index'=>'status_at',
                'type' => 'datetime',
                'width' => '100px',
            ));
        }*/

        $this->addColumn('status',
            array(
                'header'=> Mage::helper('catalog')->__('Status'),
                'width' => '70px',
                'index' => 'status',
                'type'  => 'options',
                'options' => Mage::getSingleton('catalog/product_status')->getOptionArray(),
        ));


        if (!Mage::app()->isSingleStoreMode()) {
            $this->addColumn('websites',
                array(
                    'header' => Mage::helper('catalog')->__('Websites'),
                    'width' => '100px',
                    'index' => 'websites',
                    'type' => 'options',
                    'options' => $this->getWebsite(),
                ));
        }


        //==========================
        $options = array();
        $manufacturers = Mage::getModel('zgb/manufacturer')->toOptionArray();
        foreach ($manufacturers as $manufacturer)
        {
            $options[$manufacturer['value']] = $manufacturer['label'];
        }

        $this->addColumn('manufacturer',
            array(
                'header' => Mage::helper('catalog')->__('厂商'),
                'width' => '100px',
                'index' => 'manufacturer_id',
                'type' => 'options',
                'options' => $options,
            ));

        if ($store && $store->getId())
        {
            $tag_options = array();
            $tag_items = Mage::getModel('eav/entity_attribute_option')
                ->getCollection()
                ->setStoreFilter()
                ->join('attribute', 'attribute.attribute_id=main_table.attribute_id', 'attribute_code');

            foreach ($tag_items as $tag_item) :
                if ($tag_item->getAttributeCode() == 'tag')
                    $tag_options[$tag_item->getOptionId()] = $tag_item->getValue();
            endforeach;
            $this->addColumn('tag',
                array(
                    'header' => Mage::helper('catalog')->__('标签'),
                    'width' => '60px',
                    'type' => 'options',
                    'index' => 'tag',
                    'options' => $tag_options,
                ));
        }

        $this->addColumn('action',
            array(
                'header'    => Mage::helper('catalog')->__('Action'),
                'width'     => '50px',
                'type'      => 'action',
                'getter'     => 'getId',
                'actions'   => array(
                    array(
                        'caption' => Mage::helper('catalog')->__('Edit'),
                        'url'     => array(
                            'base'=>'*/*/edit',
                            'params'=>array('store'=>$store->getId())
                        ),
                        'field'   => 'id'
                    )
                ),
                'filter'    => false,
                'sortable'  => false,
                'index'     => 'stores',
        ));

        // if (Mage::helper('catalog')->isModuleEnabled('Mage_Rss')) {
        //     $this->addRssList('rss/catalog/notifystock', Mage::helper('catalog')->__('Notify Low Stock RSS'));
        // }

        return parent::_prepareColumns();
    }

    public function filterCategoryCallback($collection, $column)
    {
        $value = $column->getFilter()->getValue();
        $_category = Mage::getModel('catalog/category')->load($value);
        $collection->addCategoryFilter($_category);
        
        return $collection;
    }

    protected function _prepareMassaction()
    {
        $zgb = Mage::helper('zgb');
        $this->setMassactionIdField('entity_id');
        $this->getMassactionBlock()->setFormFieldName('product');

        /*$storeId = 0;
        if ($this->getRequest()->getParam('store')) {
            $storeId = Mage::app()->getStore($this->getRequest()->getParam('store'))->getId();
        }*/
        $store = $this->_getStore();
        if($store){
            $websiteId = $store->getWebsiteId();
        }else{
            return false;
        }
        $storeId = $this->_getStore()->getId();

        $session = Mage::getSingleton('admin/session');
        $roleId = $session->getUser()->getRoleId();
        $roles = array($zgb->getRoleId('manufacturer'),$zgb->getRoleId('dealer'),$zgb->getRoleId('dealer'));
           // if(!in_array($roleId,$roles))
            //{
            //    $this->getMassactionBlock()->addItem('delete', array(
            //        'label'=> Mage::helper('catalog')->__('Delete'),
            //         'url'  => $this->getUrl('*/*/massDelete'),
            //         'confirm' => Mage::helper('catalog')->__('Are you sure?')
            //    ));
           // }

        $statuses = Mage::getSingleton('catalog/product_status')->getOptionArray();

        array_unshift($statuses, array('label'=>'', 'value'=>''));
        $this->getMassactionBlock()->addItem('status', array(
             'label'=> Mage::helper('catalog')->__('Change status'),
             'url'  => $this->getUrl('*/*/massStatus', array('store'=>$storeId)),
             'additional' => array(
                    'visibility' => array(
                         'name' => 'status',
                         'type' => 'select',
                         'class' => 'required-entry',
                         'label' => Mage::helper('catalog')->__('Status'),
                         'values' => $statuses
                     )
             )
        ));

        if (Mage::getSingleton('admin/session')->isAllowed('catalog/update_attributes')){
            $this->getMassactionBlock()->addItem('attributes', array(
                'label' => Mage::helper('catalog')->__('Update Attributes'),
                'url'   => $this->getUrl('*/catalog_product_action_attribute/edit', array('_current'=>true))
            ));
        }

        Mage::dispatchEvent('adminhtml_catalog_product_grid_prepare_massaction', array('block' => $this));
        return $this;
    }

    public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', array('_current'=>true));
    }

    public function getRowUrl($row)
    {
        return $this->getUrl('*/*/edit', array(
            'store'=>$this->_getStore()->getId(),
            'id'=>$row->getId())
        );
    }
    protected function getWebsite()
    {
        $websiteId =Mage::helper("qslb")->_getwebsiteId();
        $website = Mage::getModel('core/website')->getCollection()->toOptionHash();
        $outs= array();
        if (key_exists($websiteId,$website))
        {
          $websitename = $website[$websiteId];
          $outs[$websiteId]=$websitename;
          return $outs;

        }
          return $website;
    }

}
